package ioc.demo.reflect;

import ioc.demo.bean.HelloWorld;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 描述:
 *
 * @author Zhanggq
 * @date 2019/9/19 11:02
 */
public class ReflectHelloWorld {

    public void sayHello(){
        HelloWorld helloWorld = null;
        Class clazz = null;
        Constructor declaredConstructor = null;
        try {
            String className = "ioc.demo.bean.HelloWorld";
            clazz = Class.forName(className);
            declaredConstructor = clazz.getDeclaredConstructor();
            declaredConstructor.setAccessible(Boolean.TRUE);
            helloWorld = (HelloWorld) declaredConstructor.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(helloWorld.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String propName = propertyDescriptor.getName();
                Method setterMethod = propertyDescriptor.getWriteMethod();
                if (Objects.equals(propName, "name")) {
                    setterMethod.invoke(helloWorld, "中华人民共和国");
                }
                if (Objects.equals(propName, "age")) {
                    setterMethod.invoke(helloWorld, 70);
                }
            }
            helloWorld.sayHello();
        } catch (ClassNotFoundException e) {
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }

}
